package sdk.webview.fmc.com.fmcsdk.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.bean.ErrorEvnet;
import sdk.webview.fmc.com.fmcsdk.interfaces.ForgetPwdView;
import sdk.webview.fmc.com.fmcsdk.presenter.ForgetPwdPresenter;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBus;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBusSubscriber;
import sdk.webview.fmc.com.fmcsdk.view.EditPwdDialog;
import sdk.webview.fmc.com.fmcsdk.view.LoginBottomDialog;

public class ForgetPwdActivity extends BaseActivity<ForgetPwdView, ForgetPwdPresenter> implements ForgetPwdView, View.OnClickListener {
    private TitleBar titlebar;
    private EditText login_username, login_sms_code;
    private TextView tv_send_sms, tv_haoma_tip, login_changeconnect;
    private Button next;

    private EditPwdDialog editPwdDialog;
    private LoginBottomDialog loginBottomDialog;
    private String mPhone; //发送验证码返回的手机号码
    private String sendSmsUname;  //最近发送验证码的账号
    private String userStr;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_forget_pwd;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        titlebar = (TitleBar) findViewById(R.id.titlebar);
        titlebar.setTitle(getResources().getString(R.string.forget_password_title));

        login_username = (EditText) findViewById(R.id.login_username);
        login_sms_code = (EditText) findViewById(R.id.login_sms_code);
        tv_send_sms = (TextView) findViewById(R.id.tv_send_sms);
        tv_haoma_tip = (TextView) findViewById(R.id.tv_haoma_tip);
        next = (Button) findViewById(R.id.next);
        login_changeconnect = (TextView) findViewById(R.id.login_changeconnect);

        tv_send_sms.setOnClickListener(this);
        next.setOnClickListener(this);
        login_changeconnect.setOnClickListener(this);


        RxBus.getDefault().toObservable(ErrorEvnet.class).subscribe(new RxBusSubscriber<ErrorEvnet>() {
            @Override
            public void receive(ErrorEvnet data) {
                if (getResources().getString(R.string.get_sms).equals(tv_send_sms.getText().toString().trim())) {
                    Log.e("shuchang", "tv_send_sms--恢复可点击");
                    tv_send_sms.setEnabled(true);
                    tv_send_sms.setTextColor(getResources().getColor(R.color.no_send_sms));
                }
            }
        });
    }

    @Override
    protected ForgetPwdPresenter createPresenter() {
        return new ForgetPwdPresenter();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        userStr = login_username.getText().toString().trim();
        if (id == R.id.next) {
            String smsStr = login_sms_code.getText().toString().trim();

            if (TextUtils.isEmpty(mPhone)) {  //请获取验证码
                ToastUtils.showShort(context, getResources().getString(R.string.sms_shuru));
                return;
            }

            if (TextUtils.isEmpty(smsStr)) {
                ToastUtils.showShort(context, getResources().getString(R.string.msg_login_codeisnull));
                return;
            }

            if (!userStr.equals(sendSmsUname)) {
                ToastUtils.showShort(context, getResources().getString(R.string.sms_error));
                return;
            }

            //验证验证码是否成功
            sureSms(smsStr);
        } else if (id == R.id.tv_send_sms) {

            if (TextUtils.isEmpty(userStr)) {
                ToastUtils.showShort(context, getResources().getString(R.string.msg_login_usernameisnull));
                return;
            }
            if (!needIgnoreClick(v)) {
                // 发送验证码的操作
//                tv_send_sms.setEnabled(false); // 禁用按钮防止重复点击
//                tv_send_sms.setTextColor(getResources().getColor(R.color.has_send_sms));
                sendSms(userStr);
            }
        } else if (id == R.id.login_changeconnect) {
            showConnectDialog(context.getString(R.string.need_input_connect_address));
        }
    }

    private void sureSms(String smsStr) {
        String phoneCode = AESUtil.encryptAESExpand(mPhone + "&" + smsStr);
        presenter.checkForpwdSms(phoneCode);
    }

    private void sendSms(String userStr) {
        sendSmsUname = userStr;
        presenter.sendUserNameMessage(userStr);
    }

    private void startDaojishi() {
        startCountDownTimer(60000, 1000); // 倒计时60秒
        tv_send_sms.setEnabled(false); // 禁用按钮防止重复点击
        tv_send_sms.setTextColor(getResources().getColor(R.color.has_send_sms));
    }


    @Override
    public void sendSmsSuccess(String phone) {
        this.mPhone = phone;
        tv_haoma_tip.setVisibility(View.VISIBLE);
        tv_haoma_tip.setText(getResources().getString(R.string.sms_has_send_to) + StringUtils.maskPhoneNumber(phone));
        startDaojishi();
    }

    @Override
    public void sendSmsFail() {
        tv_send_sms.setEnabled(true);
        tv_send_sms.setText(getResources().getString(R.string.get_sms));
        tv_send_sms.setTextColor(getResources().getColor(R.color.no_send_sms));
    }

    @Override
    public void checkForpwdSmsSuccess() {
        showEditPwdDialog("PWD_FORGOT", userStr);
    }

    @Override
    public void updatePwdSuccess() {
        if (editPwdDialog != null) {
            editPwdDialog.dismiss();
        }
        toast("密码修改成功");
        finish();
    }

    private void showEditPwdDialog(String code, String username) {
        editPwdDialog = new EditPwdDialog(ForgetPwdActivity.this, code, username,
                new EditPwdDialog.ClickiInterface() {
                    @Override
                    public void clickSure(String username, String loginOldPwd, String loginNewPwd) {
                        presenter.editPwd(username, loginOldPwd, loginNewPwd, "1");
                    }

                    @Override
                    public void clickCancel(String pwdChangeDec) {
                        if (editPwdDialog != null) {
                            editPwdDialog.dismiss();
                        }
                    }
                });
        editPwdDialog.show();
        editPwdDialog.setType("1");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private CountDownTimer countDownTimer;

    private void startCountDownTimer(long millisInFuture, long countDownInterval) {
        countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_send_sms.setText(getResources().getString(R.string.again_get) + "(" + millisUntilFinished / 1000 + "S)");
            }

            @Override
            public void onFinish() {
                tv_send_sms.setEnabled(true);
                tv_send_sms.setText(getResources().getString(R.string.get_sms));
                tv_send_sms.setTextColor(getResources().getColor(R.color.no_send_sms));
            }
        }.start();
    }

    /**
     * 弹出地址选择
     */
    private void showConnectDialog(String msg) {

        loginBottomDialog = new LoginBottomDialog(this, msg);
        loginBottomDialog.show();
        loginBottomDialog.setClicklistener(new LoginBottomDialog.ClickListenerInterface() {
            @Override
            public void scan() {
                int permissionCheck = ContextCompat.checkSelfPermission(ForgetPwdActivity.this, Manifest.permission.CAMERA);
                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ForgetPwdActivity.this, new String[]{Manifest.permission.CAMERA}, 3);
                } else {
                    //选择扫码输入服务器地址
                    loginBottomDialog.dismiss();
                    Intent intent = new Intent(ForgetPwdActivity.this, ConnectSettingActivity.class);
                    intent.putExtra("isScan", true);
                    startActivity(intent);
                }


            }

            @Override
            public void input() {
                //手动输入地址
                loginBottomDialog.dismiss();
                Intent intent = new Intent(ForgetPwdActivity.this, ConnectSettingActivity.class);
                startActivity(intent);

            }
        });
    }

}
